package sms_interface;

/**
 * 
 * @author aayushjain
 * Once the query is authenticated and verified,we form the rest query from it to be sent as a http request
 */

public class RestQueryFormation {
	/**
	 * Once the query is authenticated and verified,we form the rest query from it to be sent as a http request
	 * @param msg message from the gsm gateway.
	 * @param date date and time of receiving the message.
	 * @return Rest Query formed from the message.
	 * @throws Exception
	 */
	public static String formQuery(String msg, String date) throws Exception{
		String arr2[] =msg.split("%");
		/*for ( int i=0;i<arr2.length;i++){
			System.out.println(arr2[i]);
		}*/
		
		String finStr=null;
		String first=arr2[2].substring(2,arr2[2].length());
		if( first.equalsIgnoreCase("get"))
		{
			String second=arr2[3].substring(2,arr2[3].length());
			if(second.equalsIgnoreCase("state"))
			{
				String last=arr2[7].substring(2,arr2[7].length());
				String room=arr2[4].substring(2,arr2[4].length());
				String appl=arr2[5].substring(2,arr2[5].length());
				finStr=last+"/state/get/"+room+"/"+appl;
			}
			else if(second.equalsIgnoreCase("data"))
			{
				String last=arr2[arr2.length-2].substring(2,arr2[arr2.length-2].length());
				String room=arr2[4].substring(2,arr2[4].length());
				String appl=arr2[5].substring(2,arr2[5].length());
				String time=arr2[6].substring(2,arr2[6].length());
				String uni=arr2[7].substring(2,arr2[7].length());
				
				String starttime;
				String endtime;
				endtime=Date.strtodate(date);
				starttime=Date.subdate(date,time, uni);
				finStr=last+"/data/get/"+room+"/"+appl+"/"+starttime+"/"+endtime;
			}
		}
		else if(first.equalsIgnoreCase("Set")){
			String last=arr2[8].substring(2,arr2[8].length());
			String room=arr2[5].substring(2,arr2[5].length());
			String appl=arr2[6].substring(2,arr2[6].length());
			String state=arr2[4].substring(2,arr2[4].length());			
			finStr=last+"/actuate/set/"+room+"/"+appl+"/"+state;
		}
		
		return finStr;
		
	}
	
	/**
	 * Testing of various valid rest query formats
	 * @param args
	 * @throws Exception
	 */
	public static void main(String [] args) throws Exception{
		System.out.println(formQuery("EN%3A%2DGet%20state%20f1%20l1%21Id%3A100%21","10.25.11 15:52:33"));
		System.out.println(formQuery("EN%3A%2DSet%20state%20ON%20f1%20l1%21Id%3A100%21","10.25.11 15:52:33"));
		System.out.println(formQuery("EN%3A%2DGet%20data%20f1%20l1%2048%20sec%21Id%3A100%21","10.25.11 15:52:33"));
	}
}
